const express = require('express')
const userDataModel = require('../model/userDataModel')
const userCodeModel = require('../model/userCodeModel')
const nodeMail = require('../utils/nodemailer')
const addDataModel = require('../model/addDataModel')
const router = express.Router()

router.post('/getUserData', async (req, res) => {
    const { mail, name, password, phone, vx } = req.body
    const resMail = await userDataModel.findOne({ mail })
    const resName = await userDataModel.findOne({ name })
    if (resMail) return res.json({ code: '404', msg: '该邮箱已注册' })
    if (resName) return res.json({ code: '404', msg: '名字已存在' })
    const min = 100000;
    const max = 999999;
    const code = Math.floor(Math.random() * (max - min + 1)) + min;
    const userMail = {
        from: 'cbb88cai@163.com',
        to: mail,
        subject: '您的验证码为：',
        text: '验证码为：' + code + '(5分钟内过期)'
    }
    nodeMail.sendMail(userMail, async (err, info) => {
        if (err) {
            res.json({ code: '404', msg: '邮箱不存在' })
            return
        }
        const expiresAt = new Date(Date.now() + 5 * 60 * 1000); // 当前时间 + 5分钟
        await userCodeModel.create({ mail, code, expiresAt, createdAt: new Date() })
        res.json({ code: '200', msg: '发送成功' })
    })

})

router.post('/getUserCode', async (req, res, next) => {
    const { mail, name, password, phone, vx, code } = req.body
    const data = await userCodeModel.findOne({ mail, code })
    if (!data) return res.json({ code: '404', msg: '验证码错误' })
    await userDataModel.create({ mail, name, password, phone, vx })
    await userCodeModel.deleteOne({ mail, code })
    res.json({ code: '200', msg: '注册成功' })
});

router.get('/userData', async (req, res, next) => {
    const data = await addDataModel.deleteMany()
    res.json({ code: "200", data })
});

module.exports = router